package com.hyzh.hj212.netty;

import com.coffee.concurrent.CoffeeExecutorManager;
import com.coffee.netty.CommandHandler;
import com.hyzh.hj212.service.LatteService;
import io.netty.channel.ChannelHandlerContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;

/**
 * @author songkui
 * @since 2024/8/5 16:19
 */
@Service
@Slf4j
@AllArgsConstructor
public class HjServerHandler implements CommandHandler {
    private final LatteService latteService;
    @Override
    public void handleCommand(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (null == msg){
            log.error("Channel msg >>> msg is null;  channel id: {}", ctx.channel().id());
            return;
        }
        log.info("Channel msg >>> channel id: {};  msg: {}", ctx.channel().id(), msg);
        Executor executor = CoffeeExecutorManager.getInstance().getDisruptor(ctx.channel().id().hashCode());
        executor = null == executor ? CoffeeExecutorManager.getInstance().getDefaultExecutor() : executor;
        executor.execute(() ->latteService.saveRecord(msg));

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("ChannelInactive connection Illegal {}", ctx.channel().toString());
    }
}
